package spider.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import spider.entity.TbConfig;

import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class HttpUtils {
    @Autowired
    RestTemplate restTemplate;

    public String httpPostJson(TbConfig tbConfig, JSONObject json) {
        HttpHeaders headers = new HttpHeaders();
        if (tbConfig.getHeaders() != null) {
            JSONObject head = JSONObject.parseObject(tbConfig.getHeaders());
            head.keySet().forEach(key -> {
                headers.add(key, head.getString(key));
            });
        }
        HttpEntity<JSONObject> formEntity = new HttpEntity<JSONObject>(json, headers);
        return restTemplate.postForEntity(tbConfig.getUrl(), formEntity, String.class).getBody();
    }

    public String httpSendForm(TbConfig tbConfig, JSONObject json) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            if (tbConfig.getHeaders() != null) {
                JSONObject head = JSONObject.parseObject(tbConfig.getHeaders());
                head.keySet().forEach(key -> {
                    headers.add(key, head.getString(key));
                });
            }
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            json.keySet().forEach(key -> {
                map.add(key, json.getString(key));
            });
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
            return restTemplate.postForObject(tbConfig.getUrl(), request, String.class);
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }

    public String httpGet(TbConfig tbConfig, String url) {
        try {
            HttpHeaders headers = new HttpHeaders();
            if (tbConfig.getHeaders() != null) {
                JSONObject head = JSONObject.parseObject(tbConfig.getHeaders());
                head.keySet().forEach(key -> {
                    headers.add(key, head.getString(key));
                });
            }
            HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
            ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            return resEntity.getBody();
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }
}
